package com.ciaojian.client.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ciaojian.core.enums.business.CouponCodeOriginEnum;
import com.ciaojian.core.enums.business.CouponCodeTakeRecordTypeEnum;
import com.ciaojian.core.enums.sys.StatusCode;
import com.ciaojian.core.mapper.CouponCodeMapper;
import com.ciaojian.core.mapper.CouponMapper;
import com.ciaojian.core.mapper.DyOrderMapper;
import com.ciaojian.core.mapper.UserMapper;
import com.ciaojian.core.model.*;
import com.ciaojian.core.model.dy.DyOrder;
import com.ciaojian.core.model.vo.CouponVo;
import com.ciaojian.core.service.CouponService;
import com.ciaojian.core.util.LogUtil;
import com.ciaojian.core.util.Result;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author Atlakyn
 */
@Service
public class CouponServiceImpl extends CouponService<CouponMapper, Coupon> implements IService<Coupon> {
    @Resource
    private CouponCodeMapper couponCodeMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DyOrderMapper dyOrderMapper;



    public void addMemberDiscount(Integer memberId, Integer userId) {
        LogUtil.writePayLog(">>>addMemberDiscount>>>memberId:{},userId:{}", memberId, userId);
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "discount_amount", "discount_count");
        queryWrapper.eq("id", memberId);
        Member dMember = new Member().selectOne(queryWrapper);
        // 如果 dMember 为空
        // 或 discountAmount(优惠数额) 为 null/0
        // 或 discountCount(优惠次数) 为 0
        // 则表示不优惠,退出方法
        if (dMember == null
                || dMember.getDiscountAmount() == null
                || dMember.getDiscountAmount().compareTo(BigDecimal.ONE) == 0
                || dMember.getDiscountCount() == 0) {
            LogUtil.writePayLog(">>>getCouponCode>>>dMember:{}", dMember);
            return;
        }

        // 用户购买会员卡获得会员减免优惠,次数为后台设置的次数
        MemberDiscount memberDiscount;
        for (Integer i = 0; i < dMember.getDiscountCount(); i++) {
            memberDiscount = new MemberDiscount();
            memberDiscount.setAmount(dMember.getDiscountAmount());
            memberDiscount.setMemberId(dMember.getId());
            memberDiscount.setUserId(userId);
            memberDiscount.setCreateTime(System.currentTimeMillis());
            memberDiscount.insert();
        }
    }

    /**
     * 券领取数量+1
     *
     * @param id 券类型
     */
    @Override
    public Boolean addGetNum(Integer id) {
        return baseMapper.addGetNumById(id);
    }

    public HashMap<String, List<CouponVo>> getCouponCode(Integer userId,
                                                         String total,
                                                         Integer storeId,
                                                         Integer serviceId,
                                                         Integer dayOfWeek) {
        HashMap<String, List<CouponVo>> map = new HashMap<>(2);
        if (total != null && !"".equals(total)) {
            List<CouponVo> usedList = couponCodeMapper.getCouponCodeByUserId(userId, total, false, storeId, serviceId, dayOfWeek);
            map.put("use", usedList);
        } else {
            List<CouponVo> useList = couponCodeMapper.getCouponCodeByUserId(userId, null, true, null, null, dayOfWeek);
            List<CouponVo> usedList = couponCodeMapper.getCouponCodeByUserId(userId, null, false, null, null, dayOfWeek);
            map.put("use", usedList);
            map.put("used", useList);
        }
        return map;
    }

    @Transactional
    public Result checkDyCoupon(Integer userId) {
        try {

            User user = userMapper.selectById(userId);
            //已经登陆过潮剪小程序的用户
            QueryWrapper<CouponCode> couponCodeQueryWrapper = new QueryWrapper<>();
            couponCodeQueryWrapper.eq("user_id",user.getId());
            couponCodeQueryWrapper.eq("coupon_id",469);
            List<CouponCode> couponCodes = couponCodeMapper.selectList(couponCodeQueryWrapper);
            if (couponCodes.size()>0) {
                return Result.error("用户已有抖音券");

            }else{
                QueryWrapper<DyOrder> dyOrderQueryWrapper = new QueryWrapper<>();
                dyOrderQueryWrapper.eq("phone_num", user.getId());
                dyOrderQueryWrapper.eq("status", 3);

                List<DyOrder> dyOrders = dyOrderMapper.selectList(dyOrderQueryWrapper);
                if (dyOrders.size() > 0) {
                    for (DyOrder dyOrder : dyOrders) {
                        QueryWrapper<CouponCode> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("coupon_id", dyOrder.getCouponId())
                                .eq("status", 0)
                                .isNull("user_id")
                                .last("limit 1");
                        CouponCode couponCode = new CouponCode().selectOne(queryWrapper);
                        Assert.notNull(couponCode, "券码已被抢完");

                        couponCode.setStatus(1);
                        couponCode.setUserId(user.getId());
                        couponCode.setOrigin(CouponCodeOriginEnum.DOUYIN_WRITE_OFF);
                        couponCode.setExpiredTime(getCouponExpiredTime(dyOrder.getCouponId()));
                        couponCode.setUpdateTime(new Date());
                        couponCode.setRemark(dyOrder.getDyOrderId());
                        couponCode.updateById();
                        Boolean aBoolean = addGetNum(dyOrder.getCouponId());

                        CouponCodeTakeRecord couponCodeTakeRecord = new CouponCodeTakeRecord();
                        couponCodeTakeRecord.setUserId(user.getId());
                        couponCodeTakeRecord.setCouponId(dyOrder.getCouponId());
                        couponCodeTakeRecord.setCouponCode(couponCode.getCode());
                        couponCodeTakeRecord.setActivityId(4);
                        couponCodeTakeRecord.setType(CouponCodeTakeRecordTypeEnum.DOUYIN_WRITE_OFF);
                        couponCodeTakeRecord.insert();
                        if (aBoolean) {
                            dyOrder.setStatus(4);
                            dyOrder.setCouponCode(couponCode.getCode());
                            dyOrder.updateById();
                            return Result.ok("领券成功", aBoolean);
                        } else {
                            return Result.ok("领券失败", aBoolean);
                        }
                    }
                }
            }
            return Result.ok("用户无抖音订单",false);
        }catch (Exception e){
            return Result.fail(StatusCode.FAIL, "接口异常",false);
        }
    }
}
